package cn.cjj.gulimall.cart.service.impl;

import cn.cjj.common.constant.AuthServerConstant;
import cn.cjj.common.constant.CartConstant;
import cn.cjj.common.utils.R;
import cn.cjj.gulimall.cart.feign.ProductFeignService;
import cn.cjj.gulimall.cart.interceptor.CartInterceptor;
import cn.cjj.gulimall.cart.service.CartService;
import cn.cjj.gulimall.cart.vo.Cart;
import cn.cjj.gulimall.cart.vo.CartItem;
import cn.cjj.gulimall.cart.vo.SkuInfoVo;
import cn.cjj.gulimall.cart.vo.UserInfoTo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author CuiJunJie
 * @create 2021/7/6-16:59
 */

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;


    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

            String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isNotEmpty(res)) {
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);

            String cartItemJson = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), cartItemJson);
            return cartItem;
        }

        CartItem cartItem = new CartItem();
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getSkuInfo(skuId);
            if (r.getCode() == 0) {
                Object skuInfoObj = r.get("skuInfo");
                String skuInfoJson = JSON.toJSONString(skuInfoObj);
                SkuInfoVo skuInfo = JSON.parseObject(skuInfoJson, SkuInfoVo.class);

                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setSkuId(skuId);
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            } else {
                log.error("远程调用getSkuInfo失败");
            }
        }, executor);

        CompletableFuture<Void> getAttrValuesTask = CompletableFuture.runAsync(() -> {
            R r = productFeignService.getSkuSaleAttrValues(skuId);
            if (r.getCode() == 0) {
                Object data = r.get("data");
                List<String> skuSaleAttrValues = JSONArray.parseArray(JSON.toJSONString(data)).toJavaList(String.class);

                cartItem.setSkuAttr(skuSaleAttrValues);
            } else {
                log.info("远程调用getSkuSaleAttrValues失败");
            }

        }, executor);


        CompletableFuture.allOf(getAttrValuesTask, getSkuInfoTask).get();

        System.out.println(cartItem);

        String cartItemJson = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(), cartItemJson);

        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        if (StringUtils.isNotEmpty(res)) {
            return JSON.parseObject(res, CartItem.class);
        }

        return null;
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        UserInfoTo user = CartInterceptor.threadLocal.get();

        Cart cart = new Cart();
        if (user.getUserId() != null) {
            List<CartItem> tempCartItems = getCartItems(CartConstant.CART_PREFIX + user.getUserKey());
            if (tempCartItems != null && tempCartItems.size() > 0) {
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
            }

            redisTemplate.delete(CartConstant.CART_PREFIX + user.getUserKey());

            List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + user.getUserId());
            cart.setItems(cartItems);
        } else {
            String cartKey = CartConstant.CART_PREFIX + user.getUserKey();

            cart.setItems(getCartItems(cartKey));
        }

        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer isChecked) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(isChecked == 1);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> currentUserCartItems() {
        UserInfoTo user = CartInterceptor.threadLocal.get();

        if (user.getUserId() == null) {
            return null;
        } else {
            List<CartItem> cartItems = getCartItems(CartConstant.CART_PREFIX + user.getUserId());
            return cartItems.stream().filter(cartItem -> {
                return cartItem.getCheck();
            }).map(cartItem -> {
                cartItem.setPrice(productFeignService.getPriceBySkuId(cartItem.getSkuId()));
                return cartItem;
            }).collect(Collectors.toList());
        }
    }

    public List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        List<Object> values = ops.values();
        if (values != null && values.size() > 0) {
            List<CartItem> cartItems = values.stream().map(value -> {
                String str = (String) value;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);

                return cartItem;
            }).collect(Collectors.toList());

            return cartItems;
        }

        return null;
    }

    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo user = CartInterceptor.threadLocal.get();
        String cartKey = "";
        if (user.getUserId() != null) {
            cartKey = CartConstant.CART_PREFIX + user.getUserId();
        } else {
            cartKey = CartConstant.CART_PREFIX + user.getUserKey();
        }

        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);

        return ops;
    }
}
